import axios from 'axios'
// import Vue from 'vue'
// import { MessageBox, Message, Notification } from 'element-ui'
import store from '@/store'
import storage from '@/utils/storage'
import router from '@/router'
// import qs from 'qs'

import { getToken } from '@/utils/auth'
import { showNotice } from '@/utils/toolclass'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: '/authority', // url = base url + request url
  // baseURL: '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000 // request timeout
})

service.interceptors.request.use(
  config => {
    /**
     * @params ENV_PORT : Number
     * 通过参数来控制网络请求端口
     * 默认端口 8001
     */
    const ENV_PORT = config.port && config.port.ENV_PORT
    if (ENV_PORT) {
      switch (ENV_PORT) {
        case 8003:
          config.baseURL = 'http://39.107.41.165:8003'
          break
        case 8004:
          config.baseURL = 'http://39.107.41.165:8004'
          break
        case 8005:
          config.baseURL = 'http://39.107.41.165:8005'
          // config.baseURL = 'http://192.168.1.105:8005'
          break
        case 8008:
          config.baseURL = 'http://39.107.41.165:8008'
          break
        case 8090: // 物联网数据临时地址
          config.baseURL = 'http://192.168.1.110:8090'
          break
        default:
          config.baseURL = 'http://39.107.41.165:8006'
          break
      }
    }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = getToken()
    }
    if (config.method === 'post') {
      // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;'
      config.headers['Content-Type'] = 'application/json'
      // config.headers['x-orgId'] = dataInfo.currentOrgId
      // console.log(config, data.currentOrgId)
      // config.data = qs.stringify(config.params)
    }
    if (config.ajaxType2 === 'reqGet') {
      const sysId = JSON.parse(storage.get('id'))
      // console.log(dataInfo)
      if (config.method === 'get') {
        const dataInfo = JSON.parse(storage.get('userInfo'))
        // console.log('get', dataInfo)
        // console.log(dataInfo.orgList)
        // config.headers['x-token'] = getToken()
        if (dataInfo !== null) {
          config.headers['x-orgId'] = dataInfo.orgList[0].id
        }
        config.headers['x-sysId'] = sysId === null ? 2 : sysId
      }
    }
    if (config.ajaxType2 === 'reqPost') {
      const dataInfo = JSON.parse(storage.get('userInfo'))
      const sysId = JSON.parse(storage.get('id'))
      if (config.method === 'post') {
        // console.log('post', dataInfo)
        // config.headers['x-token'] = getToken()
        config.headers['x-orgId'] = dataInfo.orgList[0].id
        config.headers['x-sysId'] = sysId === null ? 2 : sysId
      }
    }
    if (config.ajaxType2 === 'reqPut') {
      const dataInfo = JSON.parse(storage.get('userInfo'))
      const sysId = JSON.parse(storage.get('id'))
      if (config.method === 'put') {
        // console.log('put', dataInfo)
        // config.headers['x-token'] = getToken()
        config.headers['x-orgId'] = dataInfo.orgList[0].id
        config.headers['x-sysId'] = sysId === null ? 2 : sysId
      }
    }
    if (config.ajaxType2 === 'reqDelete') {
      const dataInfo = JSON.parse(storage.get('userInfo'))
      const sysId = JSON.parse(storage.get('id'))
      if (config.method === 'delete') {
        // console.log('delete', dataInfo)
        // config.headers['x-token'] = getToken()
        config.headers['x-orgId'] = dataInfo.orgList[0].id
        config.headers['x-sysId'] = sysId === null ? 2 : sysId
      }
    }
    if (config.ajaxType === 'formdata') {
      // console.log('formdata提交~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
      // console.log(config)
      config.headers['Content-Type'] = 'multipart/form-data'
      // config.data = qs.stringify(config.params)
    }
    // if (config.ajaxType === 'formdata1') {
    //   console.log('formdata提交~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    //   // console.log(config)
    //   config.headers['Content-Type'] = 'application/json'
    //   config.headers['Content-Type'] = 'multipart/form-data'
    //   // config.data = qs.stringify(config.params)
    // }
    // if (config.ajaxType === 'formdata') {
    //   console.log('formdata提交~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    //   console.log(config)
    //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded;'
    //   // config.data = qs.stringify(config.params)
    // }

    if (config.ajaxType === 'image') {
      // console.log('formdata-image提交~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
      // console.log(config)
      config.headers['Content-Type'] = 'image/jpeg'
      config.headers['responseType'] = 'arraybuffer'
      // config.data = qs.stringify(config.params)
    }

    if (config.ajaxType === 'applicationJson') {
      // console.log('applicationJson提交~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
      // console.log(config)
      config.headers['Content-Type'] = 'application/json'
      // config.data = qs.stringify(config.params)
    }

    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // console.log(response)
    // console.log(router)
    // console.log(response)
    if (res.code === '555555') {
      if (router.currentRoute.path === '/' || router.currentRoute.path === '/register' || router.currentRoute.path === '/wxreg') {
        // return
      } else {
        router.replace({ path: '/' })
        showNotice('warning', '提示', '您已退出，请重新登陆')
      }
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '000000') {
      // showNotice('error', '提示', res.msg)
      return res
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //   // to re-login
      //   MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
      //     confirmButtonText: 'Re-Login',
      //     cancelButtonText: 'Cancel',
      //     type: 'warning'
      //   }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // }
      // return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log(res)
      return Promise.resolve(res)
    }
  },
  error => {
    // console.log('err', error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // location.reload()
    showNotice('error', '提示', '服务器请求超时...')
    return Promise.reject(error)
  }
)

export default service
